//SPDX-FileCopyrightText: Copyright 2022-2024 深圳市同心圆网络有限公司
//SPDX-License-Identifier: GPL-3.0-only

package events_subscribe

import (
	"context"
	"fmt"

	"atomgit.com/openlinksaas/api-server/dao/event_dao"
	"atomgit.com/openlinksaas/proto-gen-go.git/events_api"
	"atomgit.com/openlinksaas/proto-gen-go.git/events_subscribe_api"
	"google.golang.org/protobuf/proto"
)

type CfgItem struct {
	subItem  *event_dao.SubscribeInfoDbItem
	eventCfg *events_subscribe_api.EventCfg
}

func DispatchEvent(event *events_api.Event) error {

	defer func() {
		err2 := recover()
		fmt.Println(err2)
	}()

	subItemList, err := event_dao.SubscribeDao.List(context.Background(), event.ProjectId)
	if err != nil {
		return err
	}
	cfgItemList := []*CfgItem{}
	for _, subItem := range subItemList {
		eventCfg := &events_subscribe_api.EventCfg{}
		err = proto.Unmarshal(subItem.EventCfgData, eventCfg)
		if err != nil {
			return err
		}
		if eventCfg.AtomgitEvCfg == nil {
			eventCfg.AtomgitEvCfg = &events_subscribe_api.AtomgitEvCfg{}
		}
		if eventCfg.HarborEvCfg == nil {
			eventCfg.HarborEvCfg = &events_subscribe_api.HarborEvCfg{}
		}
		if eventCfg.TestcaseEvCfg == nil {
			eventCfg.TestcaseEvCfg = &events_subscribe_api.TestcaseEvCfg{}
		}
		cfgItemList = append(cfgItemList, &CfgItem{
			subItem:  subItem,
			eventCfg: eventCfg,
		})
	}

	ok, err := processProjectEvent(event, cfgItemList)
	if err != nil {
		return err
	}
	if ok {
		return nil
	}

	ok, err = processExtEvent(event, cfgItemList)
	if err != nil {
		return err
	}
	if ok {
		return nil
	}

	ok, err = processGiteeEvent(event, cfgItemList)
	if err != nil {
		return err
	}
	if ok {
		return nil
	}

	ok, err = processGitlabEvent(event, cfgItemList)
	if err != nil {
		return err
	}
	if ok {
		return nil
	}

	ok, err = processIssueEvent(event, cfgItemList)
	if err != nil {
		return err
	}
	if ok {
		return nil
	}

	ok, err = processRequirementEvent(event, cfgItemList)
	if err != nil {
		return err
	}
	if ok {
		return nil
	}

	ok, err = processCodeEvent(event, cfgItemList)
	if err != nil {
		return err
	}
	if ok {
		return nil
	}

	ok, err = processIdeaEvent(event, cfgItemList)
	if err != nil {
		return err
	}
	if ok {
		return nil
	}

	ok, err = processAtomGitEvent(event, cfgItemList)
	if err != nil {
		return err
	}
	if ok {
		return nil
	}

	ok, err = processEntryEvent(event, cfgItemList)
	if err != nil {
		return err
	}
	if ok {
		return nil
	}

	ok, err = processHarborEvent(event, cfgItemList)
	if err != nil {
		return err
	}
	if ok {
		return nil
	}

	ok, err = processTestCaseEvent(event, cfgItemList)
	if err != nil {
		return err
	}
	if ok {
		return nil
	}

	ok, err = processDataAnnoEvent(event, cfgItemList)
	if err != nil {
		return err
	}
	if ok {
		return nil
	}

	return nil
}
